package com.jasiri.project.ui.credit.page

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.jasiri.lib.permission.Permission
import com.jasiri.lib.permission.XXPermissions
import com.jasiri.project.adapter.AmountAdapter
import com.jasiri.project.analysis.TestDataLibInvoke
import com.jasiri.project.app.App
import com.jasiri.project.databinding.PageLimitBinding
import com.jasiri.project.pro.ProFragment
import com.jasiri.project.ui.credit.activity.ApplyActivity
import com.jasiri.project.ui.permission.PermissionReasonActivity
import com.jasiri.project.ui.process.activity.ProcessActivity
import com.jasiri.project.utils.config.Configs
import com.jasiri.project.utils.dialog.LimitImproveDialog
import com.jasiri.project.utils.event.EventType
import com.jasiri.project.utils.event.track.TrackEventManager
import com.jasiri.project.utils.http.AppUrls
import com.jasiri.project.utils.http.AppUrls.addCommonParams
import com.jasiri.project.utils.http.IHttpCallback
import org.greenrobot.eventbus.EventBus
import org.json.JSONObject

/**
 * Sikadwa
 * @Author wwdeng
 * @CreateTime: 2024/5/22 17:44
 * @Annotation：贷款额度
 */
class LimitPage(): ProFragment() {
    private var _binding: PageLimitBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "Cannot access binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )
    var isComplete = false

    private var limitInfo: JSONObject? = null
    private var mAmountAdapter: AmountAdapter? = null
    override fun getRootView(inflater: LayoutInflater): View {
        _binding = PageLimitBinding.inflate(inflater)
        return binding.root
    }

    constructor(isComplete: Boolean): this(){
        this.isComplete = isComplete
    }

    override fun initView() {
        _binding?.parentLayout?.setPadding(0,
            com.jasiri.project.utils.BarUtils.getStatusBarHeight(),0,0)
        initRefreshView()
        initRvAmount()
        showStateView()
    }

    override fun initListener() {
        //个人中心
        _binding?.imgUser?.setOnClickListener {
            showPersonalDialog("CreditLimit Page")
            addEvent(EventType.CLICK.CLICK_USER,"CreditLimit Page")
        }
        //客服
        _binding?.imgKefu?.setOnClickListener {
            showKefuDialog("CreditLimit Page")
            addEvent(EventType.CLICK.CLICK_CUSTOMER,"CreditLimit Page")
        }
        //完善流程
        _binding?.btnGetStarted?.setOnClickListener {
//            addEvent(EventType.CLICK.CLICK_CREDIT_LIMIT_ADD_INFORMATION,"")
            //立即上报
            TrackEventManager.trackEventNow(EventType.CLICK.CLICK_CREDIT_LIMIT_ADD_INFORMATION,"")
            checkAllPermissions()
        }
        //申请贷款
        _binding?.btnCheck?.setOnClickListener {
//            addEvent(EventType.CLICK.CLICK_CREDIT_LIMIT_CHECK,"")
            //立即上报
            TrackEventManager.trackEventNow(EventType.CLICK.CLICK_CREDIT_LIMIT_CHECK,"")
            checkAllPermissions()
        }
    }

    override fun initData() {
        addEvent(EventType.PAGE.PAGE_CREDIT_LIMIT_START,"")
    }

    /**
     * 权限声明列表
     */
    private val permissionReasonResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        when (result.resultCode) {
            Activity.RESULT_OK -> {
                var isNext = false
                result.data?.let { bundle ->
                    val isAgree = bundle.getBooleanExtra("isPermissionAgree",false)
                    //同意，校验权限 进行下一步
                    isNext = if (isAgree){
                        true
                    } else {//拒绝，
                        //是否是广告渠道
                        val isAdSource = Configs.getSPBoolean(Configs.SPKEY.JASIRI_IS_ADSOURCE)
                        //非广告渠道才继续校验进行下一步
                        !isAdSource
                    }
                }
                if (isNext){
                    checkAllPermissions()
                }
            }
        }
    }

    /* 初始化刷新 */
    private fun initRefreshView() {
        //禁止加载
        _binding?.refreshLayout?.setEnableLoadMore(false)
        _binding?.refreshLayout?.setEnableAutoLoadMore(false)
        _binding?.refreshLayout?.setOnRefreshListener {
            //发送刷新流程通知
            EventBus.getDefault().post(Configs.Event.PROCESS_REFRESH)
        }
        _binding?.refreshLayout?.setOnLoadMoreListener {
            _binding?.refreshLayout?.finishLoadMore()
        }
    }

    private fun initRvAmount(){
        _binding?.rvAmount?.setHasFixedSize(true)
        _binding?.rvAmount?.isNestedScrollingEnabled = false
        _binding?.rvAmount?.isFocusableInTouchMode = false //不需要焦点
        val decoration = com.jasiri.project.utils.DensityUtils.dp2px(14f)
        _binding?.rvAmount?.addItemDecoration(
            com.jasiri.project.utils.rv.LinearDecoration(
                0,
                decoration,
                0,
                0
            )
        )
        val layoutManager = LinearLayoutManager(requireContext())
        layoutManager.orientation = RecyclerView.HORIZONTAL
        _binding?.rvAmount?.layoutManager = layoutManager
        mAmountAdapter = AmountAdapter(_binding?.rvAmount)
        mAmountAdapter?.setOnItemChildClickListener { parent, childView, position ->
            val item = this.mAmountAdapter?.getItem(position)
        }
        _binding?.rvAmount?.adapter = mAmountAdapter
    }

    /**
     * 显示样式
     */
    fun showStateView(){
        when(isComplete){
            true -> {//已完成 - 显示额度
                _binding?.processLayout?.visibility = View.GONE
                _binding?.limitLayout?.visibility = View.VISIBLE
                _binding?.successTipsLayout?.visibility = View.VISIBLE
            }
            else -> {//未完成 - 显示完善资料
                _binding?.processLayout?.visibility = View.VISIBLE
                _binding?.limitLayout?.visibility = View.GONE
                _binding?.successTipsLayout?.visibility = View.GONE
            }
        }
        loadLimitAction()
    }

    /**
     * 进入权限声明列表
     */
    private fun enterPermissionReason(){
        limitInfo?.let {
            val showAmount = it.optString("showAmount")
            val unit = it.optString("currency")
            val intent = Intent(context, PermissionReasonActivity::class.java)
            intent.putExtra("amount", showAmount)
            permissionReasonResultLauncher.launch(intent)
        }
    }

    /**
     * 申请
     */
    private fun enterApply(){
        onIntent(ApplyActivity::class.java)
    }

    /**
     * 完善流程
     */
    private fun enterProcess(){
        limitInfo?.let {
            val showAmount = it.optString("showAmount")
            ProcessActivity.start(requireContext(),showAmount)
        }
    }

    /**
     * 设置显示额度
     */
    @SuppressLint("SetTextI18n")
    private fun showLimitData(data: JSONObject){
        val amountList = arrayListOf<String>()
        var amountString = data.optString("amount1")
        if (isComplete){
            amountString = data.optString("amount")
        }
        limitInfo = data
        limitInfo?.put("showAmount",amountString)

        for (i in amountString.indices){
            amountList.add(amountString[i].toString())
        }
        mAmountAdapter?.data = amountList
        _binding?.textSignAmount?.text = "+" + data.optString("amount2")
        _binding?.textProfileAmount?.text = "+" + data.optString("amount3")

        _binding?.textLimitAmount?.text = data.optString("amount")

        //加载额度是否有提升
        loadLimitIncreasedStatusAction()
    }

    /**
     * 额度提升dialog
     */
    private fun showLimitIncreasedDialog(data: JSONObject){
        val dialog = LimitImproveDialog(requireContext(),object : LimitImproveDialog.IDialogCallback{
            override fun onClick(view: View?) {
                _binding?.btnCheck?.callOnClick()
            }
        })
        dialog.setCancelable(true)
        dialog.setCanceledOnTouchOutside(false)
        dialog.show()
        dialog.showLimitImprovedData(data)
    }

    /**
     * 检查是否授权所有权限
     */
    private fun checkAllPermissions(){
        //权限页操作状态 : 0未操作  1已同意  -1拒绝
        val permissionReasonStatus = Configs.getSPInt(Configs.SPKEY.JASIRI_PERMISSION_REASON_STATUS)
        //权限列表未操作 -> 进入权限列表
        if (permissionReasonStatus == 0){
            enterPermissionReason()
            return
        }

        //是否是广告渠道
        val isAdSource = Configs.getSPBoolean(Configs.SPKEY.JASIRI_IS_ADSOURCE)
        //广告渠道 && 权限列表未同意 -> 进入权限列表
        if (isAdSource && permissionReasonStatus == -1){
            enterPermissionReason()
            return
        }
        //广告渠道 && 未同意sms权限 -> 进入权限列表
        if (isAdSource && !XXPermissions.isGranted(requireContext(), arrayListOf(Permission.READ_SMS,Permission.ACCESS_COARSE_LOCATION))){
            enterPermissionReason()
            return
        }

        //已同意权限列表 && 已同意SMS权限 -> 上报设备数据
        if (permissionReasonStatus == 1 && XXPermissions.isGranted(requireContext(), Permission.READ_SMS)){
            //注册传感器监听
            App.instance().registerSensor()
            //上报设备数据
            TestDataLibInvoke.loadDInfoTypeAction()
        }
        if (isComplete){
            enterApply()
        } else {
            enterProcess()
        }
    }

    /**
     * 获取贷款额度
     */
    private fun loadLimitAction(){
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.COMMON)
        val params = JSONObject().addCommonParams().apply {
            put("path", AppUrls.PATH.LIMIT)
        }
        postAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                //需要显示的金额JSON
                var amountObject: JSONObject? = null
                //未完善资料之前，显示额度从启动页配置数据中取
                val commonData = getCommonObject()
                val customize = commonData.optJSONObject("customize")
                if (customize != null){
                    amountObject = customize.optJSONObject("loanLimit")
                }
                //后台没有配置loanLimit 默认额度
                if (amountObject == null){
                    amountObject = JSONObject()
                    amountObject.put("amount1","35000")
                    amountObject.put("amount2","15000")
                    amountObject.put("amount3","20000")

                }

                //完善资料之后显示的可申请金额需要从贷款额度接口中取 amount
                val limitArray = obj?.optJSONArray("limit")
                limitArray?.let {
                    if (it.length() > 0){
                        val limitObj = it.optJSONObject(0)
                        amountObject.put("amount",limitObj.optString("amount"))
                        amountObject.put("currency",limitObj.optString("currency"))
                    }
                }
                showLimitData(amountObject)
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
                _binding?.refreshLayout?.finishRefresh()
            }
        })
    }

    /**
     * 检查额度是否增加
     */
    private fun loadLimitIncreasedStatusAction(){
        val params = JSONObject()
            .addCommonParams()
            .apply {
                put("path",AppUrls.PATH.LIMIT_INCREASED_PATH)
            }
        //todo 测试提额dialog
//        params.put("selectAmount","2000")
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.COMMON)
        postAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                if (obj != null && obj.optString("openFlag") == "YES"){
                    showLimitIncreasedDialog(obj)
                }
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
            }
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        addEvent(EventType.PAGE.PAGE_CREDIT_LIMIT_END,"")
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}